<?php

// application/models/GuestbookMapper.php

class Application_Model_ProjectMapper {

    protected $_dbTable;

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Project');
        }
        return $this->_dbTable;
    }

    public function save(Application_Model_Project $project) {
        $data = array(
            'name' => $project->getName(),
            'svn_url' => $project->getSvn_url(),
            'code' => $project->getCode(),
            'user_id' => $project->getUser_id(),
            'host_ip' => $project->getHost_ip(),
            'host_acc' => $project->getHost_acc(),
            'db_acc' => $project->getDb_acc(),
            'db_pass' => $project->getDb_pass(),
            'active'=> $project->getActive()
        );

        if (null === ($id = $guestbook->getId())) {
            unset($data['id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }

    public function find($id) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $project = new Application_Model_Project($this->convertProjectSetToArray($row));
        return $project;
    }

    public function fetchAll() {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_Project($this->convertProjectSetToArray($row));
            $entries[] = $entry;
        }
        return $entries;
    }
    public function convertProjectSetToArray($resultSet){
        return  array(
            'id' => $resultSet->id,
            'name' => $resultSet->name,
            'svn_url' => $resultSet->svn_url,
            'code' => $resultSet->code,
            'user_id' => $resultSet->user_id,
            'host_ip' => $resultSet->host_ip,
            'host_acc' => $resultSet->host_acc,
            'db_acc' => $resultSet->db_acc,
            'db_pass' => $resultSet->db_pass,
            'active'=> $resultSet->active
        );
    }
}